//
// Created by 刘禹晨 on 16/5/25.
// Copyright (c) 2016 刘禹晨. All rights reserved.
//

#import "NodeViewController.h"
#import "CBHelper.h"
#import "ZigbeeModel.h"
#import <JSONKit/JSONKit.h>
#import "AppDelegate.h"

#define kW [UIScreen mainScreen].bounds.size.width
#define kH [UIScreen mainScreen].bounds.size.height

@interface NodeViewController() <UIWebViewDelegate>

{
    UIWebView *nodeWebView;
    UINavigationBar *_navigationBar;
    UINavigationItem *_uiNavigationItem;
    CBHelper *_cbHelper;
    NSString *json;
    AppDelegate *delegate;
}

@end

@implementation NodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //[self initNavigationBar];
    delegate = [UIApplication sharedApplication].delegate;
    self.navigationItem.title = @"网络结构图";
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(WebViewReload:)];
    self.navigationItem.rightBarButtonItem = right;
    nodeWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kW, kH - 48)];
    //nodeWebView.userInteractionEnabled = NO;
    nodeWebView.scrollView.bounces = NO;
    [self.view addSubview:nodeWebView];
    //[self.view addSubview:_navigationBar];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateWebView) name:@"updateWebView" object:nil];
    _cbHelper = [CBHelper alloc];
    [self createNodeAndChilde:_cbHelper._zigbees];
    NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];
    NSString *filePath  = [resourcePath stringByAppendingPathComponent:@"node.html"];
    //NSString *htmlstring =[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //[nodeWebView loadHTMLString:htmlstring  baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle]  bundlePath]]];
    [nodeWebView loadRequest:request];
    nodeWebView.delegate = self;
    UIBarButtonItem *leftMenuButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"list_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(openLeftMenu:)];
    self.navigationItem.leftBarButtonItem = leftMenuButton;
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

-(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"NodeViewController Did Appear");
    [delegate.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [delegate.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
}

-(void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"NodeViewController Will DisAppear");
    [delegate.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    [delegate.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeNone];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)openLeftMenu:(id)sender
{
    [delegate.drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];//左侧打开关闭侧边栏方法
}

-(void)WebViewReload:(id)sender
{
    [self createNodeAndChilde:_cbHelper._zigbees];
    [nodeWebView reload];
}

-(void)updateWebView
{
    [self createNodeAndChilde:_cbHelper._zigbees];
    NSString *param = [NSString stringWithFormat: @"createWeb('%@');",json];
    NSString *result = [nodeWebView stringByEvaluatingJavaScriptFromString:param];
    NSLog(@"Update WebView : %@",result);

}

-(void)createNodeAndChilde:(NSMutableArray*) nodes
{
    for(ZigbeeModel *obj in nodes)
    {
        [obj clearDictonary];
    }
    for(ZigbeeModel *obj in nodes)
    {
        [obj createDictionary];
    }
    for(ZigbeeModel *obj in nodes)
    {
        for(ZigbeeModel *childe in nodes){
            if([obj.NodeNetworkAddress isEqualToString:childe.ParentNetworkAddress])
            {
                //[childe createDictionary];
                [obj.childrenList addObject:childe.nodeDict];
            }
        }
    }
    for(ZigbeeModel *obj in nodes)
    {
        if([obj.NodeType isEqualToString:@"C"])
        {
            json = [obj.nodeDict JSONString];
        }
    }
    NSLog(@"%@",json);
}


-(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    NSLog(@"加载失败,ERROR");
}

-(void)webViewDidStartLoad:(nonnull UIWebView *)webView{
    NSLog(@"开始加载");
}


-(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{
    NSLog(@"开始结束");
    NSString *param = [NSString stringWithFormat: @"createWeb('%@');",json];
    NSString *result = [webView stringByEvaluatingJavaScriptFromString:param];
    NSLog(@"%@",result);
}

/**
 * 设置白色状态栏
 */
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


@end